﻿using CSRedis;
using Demo.Net.Service.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using StackExchange.Redis;

namespace Demo.Net.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RedisController : ControllerBase
    {
        private readonly CSRedisClient _redisClient;
        public RedisController(CSRedisClient redisClient)
        {
            _redisClient = redisClient;
        }


        /// <summary>
        /// Redis测试
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> RedisTest()
        {

             await _redisClient.SetAsync("name", "张三");
            await _redisClient.SetAsync("name2", "李四");

            return Ok(await _redisClient.GetAsync<string>("name"));

        }

        /// <summary>
        /// 移除
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> RedisRemove()
        {
            await _redisClient.DelAsync("name","name2");
            return Ok();
        }


        //批量操作

        [HttpGet]
        public async Task<IActionResult> RedisMDo()
        {

            //两组为一个键值对，需要 成对才可以
            await _redisClient.MSetAsync(new string[] { 
                    "name1","张三","name2","李四"
            });

            var result =await _redisClient.MGetAsync<string>("name1", "name2");

            return Ok(result);
        }


        //哈希操作

        [HttpGet]
        public async Task<IActionResult> RedisHash()
        {
            List<int> list = new List<int>() { 1, 2, 3, 5 };
            await _redisClient.HSetAsync("u", "b", list);
            var result = await _redisClient.HGetAsync("u", "b");
            return Ok(result);
        }

        //集合操作

        [HttpGet]
        public async Task<IActionResult> RedisList()
        {
            List<int> list = new List<int>() { 1, 2, 3, 5 };
            await _redisClient.SAddAsync("listkey", list);
            var result = await _redisClient.SMembersAsync("listkey");
            return Ok(result);
        }


    }
}
